<template>
  <div class="execution-view min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <div class="container max-w-6xl mx-auto p-6">
      <!-- 页面标题 -->
      <div class="header bg-gradient-to-r from-primary to-secondary text-white p-8 rounded-2xl mb-6 text-center">
        <h1 class="text-3xl font-bold mb-3">脚本执行反馈系统</h1>
        <p class="text-lg opacity-90">查看录制脚本的执行结果和网址转换反馈</p>
      </div>

      <!-- 任务输入区域 -->
      <div class="task-input bg-white rounded-xl shadow-lg p-6 mb-6">
        <div class="flex flex-col md:flex-row gap-4 items-end">
          <div class="flex-1">
            <label class="block text-sm font-medium text-gray-700 mb-2">任务ID</label>
            <el-input
              v-model="taskId"
              placeholder="请输入任务ID (例如: 12345678-1234-1234-1234-123456789012)"
              size="large"
              clearable
            >
              <template #prefix>
                <el-icon><i-ep-key /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="flex gap-3">
            <el-button 
              type="primary" 
              size="large"
              :loading="loading"
              @click="executeWithFeedback"
              :disabled="!taskId.trim()"
            >
              <el-icon class="mr-2"><i-ep-pie-chart /></el-icon>
              执行并获取反馈
            </el-button>
            <el-button 
              type="info" 
              size="large"
              :loading="loading"
              @click="parseOnly"
              :disabled="!taskId.trim()"
            >
              <el-icon class="mr-2"><i-ep-search /></el-icon>
              仅解析步骤
            </el-button>
            <el-button 
              type="success" 
              size="large"
              :loading="loading"
              @click="analyzeUrls"
              :disabled="!taskId.trim()"
            >
              <el-icon class="mr-2"><i-ep-link /></el-icon>
              分析URL转换
            </el-button>
          </div>
        </div>
      </div>

      <!-- 结果展示区域 -->
      <div v-if="showResults" class="results-section">
        <!-- 执行摘要卡片 -->
        <div class="summary-card bg-gradient-to-br from-primary to-secondary text-white p-8 rounded-xl mb-6">
          <h2 class="text-2xl font-bold mb-6 flex items-center">
            <el-icon class="mr-3 text-2xl"><i-ep-data-analysis /></el-icon>
            执行摘要
          </h2>
          <div class="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div class="stat-item text-center">
              <div class="stat-value text-4xl font-bold mb-2">{{ summary.totalSteps }}</div>
              <div class="stat-label text-lg opacity-80">总步骤</div>
            </div>
            <div class="stat-item text-center">
              <div class="stat-value text-4xl font-bold mb-2">{{ summary.successSteps }}</div>
              <div class="stat-label text-lg opacity-80">成功步骤</div>
            </div>
            <div class="stat-item text-center">
              <div class="stat-value text-4xl font-bold mb-2">{{ summary.successRate }}%</div>
              <div class="stat-label text-lg opacity-80">成功率</div>
            </div>
            <div class="stat-item text-center">
              <div class="stat-value text-4xl font-bold mb-2">{{ summary.duration }}ms</div>
              <div class="stat-label text-lg opacity-80">执行时间</div>
            </div>
          </div>
        </div>

        <!-- 主要结果区域 -->
        <div class="grid lg:grid-cols-2 gap-6">
          <!-- 步骤执行反馈 -->
          <div class="panel bg-white rounded-xl shadow-lg p-6">
            <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
              <el-icon class="mr-2 text-blue-500"><i-ep-refresh /></el-icon>
              步骤执行反馈
            </h3>
            
            <div v-if="stepFeedback.length > 0" class="space-y-3 max-h-96 overflow-y-auto">
              <div
                v-for="step in stepFeedback"
                :key="step.stepNumber"
                class="step-item rounded-lg border-l-4 p-4 transition-all duration-300 hover:shadow-md"
                :class="getStepItemClasses(step)"
              >
                <div class="flex items-center">
                  <div class="step-icon text-2xl mr-4">{{ getStepIcon(step) }}</div>
                  <div class="flex-1">
                    <div class="step-title font-semibold mb-1">
                      步骤 {{ step.stepNumber }}: {{ step.action || '未知操作' }}
                    </div>
                    <div class="step-details text-sm text-gray-600">
                      状态: <span :class="getStatusTextClass(step)">{{ step.status || '未知' }}</span>
                      <span class="mx-2">|</span>
                      耗时: {{ step.duration || 0 }}ms
                      <span v-if="step.message" class="mx-2">|</span>
                      <span v-if="step.message">{{ step.message }}</span>
                    </div>
                    <div v-if="step.urlChanged" class="step-url text-xs text-blue-600 mt-2">
                      🌐 {{ step.beforeUrl || '' }} → {{ step.afterUrl || '' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div v-else class="empty-state text-center py-12 text-gray-500">
              <el-icon class="text-4xl mb-3"><i-ep-document /></el-icon>
              <p>暂无步骤反馈数据</p>
            </div>
          </div>

          <!-- URL转换分析 -->
          <div class="panel bg-white rounded-xl shadow-lg p-6">
            <h3 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
              <el-icon class="mr-2 text-green-500"><i-ep-connection /></el-icon>
              网址转换分析
            </h3>

            <div v-if="urlAnalysisData" class="url-analysis">
              <div class="bg-gray-50 p-4 rounded-lg border max-h-96 overflow-auto">
                <pre class="text-sm font-mono whitespace-pre-wrap">{{ urlAnalysisData }}</pre>
              </div>
            </div>

            <div v-else class="empty-state text-center py-12 text-gray-500">
              <el-icon class="text-4xl mb-3"><i-ep-link /></el-icon>
              <p>暂无URL转换数据</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container bg-white rounded-xl shadow-lg p-12 text-center">
        <el-icon class="text-6xl text-primary animate-spin mb-4"><i-ep-loading /></el-icon>
        <p class="text-lg text-gray-600">{{ loadingText }}</p>
      </div>

      <!-- 错误状态 -->
      <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        :closable="true"
        show-icon
        @close="errorMessage = ''"
        class="mb-6"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// Element Plus 图标
import {
  Key as iEpKey,
  PieChart as iEpPieChart,
  Search as iEpSearch,
  Link as iEpLink,
  DataAnalysis as iEpDataAnalysis,
  Refresh as iEpRefresh,
  Connection as iEpConnection,
  Document as iEpDocument,
  Loading as iEpLoading
} from '@element-plus/icons-vue'

// 响应式数据
const taskId = ref('')
const loading = ref(false)
const loadingText = ref('正在处理中，请稍候...')
const showResults = ref(false)
const errorMessage = ref('')

// 结果数据
const summary = ref({
  totalSteps: 0,
  successSteps: 0,
  successRate: 0,
  duration: 0
})

const stepFeedback = ref([])
const urlAnalysisData = ref('')

// API基础地址
const API_BASE = 'http://localhost:8080/api/commands'

// 方法
const executeWithFeedback = async () => {
  if (!taskId.value.trim()) {
    ElMessage.warning('请输入任务ID')
    return
  }

  loading.value = true
  loadingText.value = '正在执行脚本并获取反馈...'
  errorMessage.value = ''

  try {
    const response = await fetch(`${API_BASE}/recording/execute-with-feedback/${taskId.value}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.success) {
      displayFeedbackResults(result.data)
      showResults.value = true
      ElMessage.success('执行反馈获取成功')
    } else {
      throw new Error(result.message || '执行失败')
    }
  } catch (error) {
    errorMessage.value = '网络错误: ' + error.message
    ElMessage.error('执行失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const parseOnly = async () => {
  if (!taskId.value.trim()) {
    ElMessage.warning('请输入任务ID')
    return
  }

  loading.value = true
  loadingText.value = '正在解析步骤...'
  errorMessage.value = ''

  try {
    const response = await fetch(`${API_BASE}/recording/parse/${taskId.value}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.success) {
      displayParseResults(result.data)
      showResults.value = true
      ElMessage.success('步骤解析成功')
    } else {
      throw new Error(result.message || '解析失败')
    }
  } catch (error) {
    errorMessage.value = '网络错误: ' + error.message
    ElMessage.error('解析失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const analyzeUrls = async () => {
  if (!taskId.value.trim()) {
    ElMessage.warning('请输入任务ID')
    return
  }

  loading.value = true
  loadingText.value = '正在分析URL转换...'
  errorMessage.value = ''

  try {
    const response = await fetch(`${API_BASE}/recording/analyze-urls/${taskId.value}`)
    const result = await response.json()

    if (result.success) {
      displayUrlAnalysis(result.data)
      showResults.value = true
      ElMessage.success('URL分析成功')
    } else {
      throw new Error(result.message || '分析失败')
    }
  } catch (error) {
    errorMessage.value = '网络错误: ' + error.message
    ElMessage.error('分析失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const displayFeedbackResults = (data) => {
  // 显示执行摘要
  if (data.summary) {
    summary.value = {
      totalSteps: data.summary.totalSteps || 0,
      successSteps: data.summary.successSteps || 0,
      successRate: parseFloat((data.summary.successRate || 0).toFixed(1)),
      duration: data.summary.duration || 0
    }
  }

  // 显示步骤反馈
  stepFeedback.value = data.stepFeedback || []

  // 显示URL转换分析
  urlAnalysisData.value = data.urlTransitionAnalysis || ''
}

const displayParseResults = (data) => {
  // 清空摘要数据（因为没有执行）
  summary.value = {
    totalSteps: data.totalSteps || 0,
    successSteps: 0,
    successRate: 0,
    duration: 0
  }

  // 转换解析的步骤为反馈格式
  stepFeedback.value = (data.steps || []).map(step => ({
    stepNumber: step.stepNumber,
    action: step.action,
    status: 'parsed',
    stepType: step.stepType,
    selector: step.selector,
    value: step.value
  }))

  // 显示URL转换分析
  urlAnalysisData.value = data.urlTransitions || ''
}

const displayUrlAnalysis = (data) => {
  urlAnalysisData.value = data.transitions || ''
  
  // 重置其他数据
  summary.value = {
    totalSteps: 0,
    successSteps: 0,
    successRate: 0,
    duration: 0
  }
  stepFeedback.value = []
}

const getStepItemClasses = (step) => {
  const status = (step.status || '').toLowerCase()
  switch (status) {
    case 'success':
      return 'border-green-400 bg-green-50'
    case 'failed':
      return 'border-red-400 bg-red-50'
    case 'timeout':
      return 'border-yellow-400 bg-yellow-50'
    case 'parsed':
      return 'border-blue-400 bg-blue-50'
    default:
      return 'border-gray-300 bg-gray-50'
  }
}

const getStatusTextClass = (step) => {
  const status = (step.status || '').toLowerCase()
  switch (status) {
    case 'success':
      return 'text-green-600 font-medium'
    case 'failed':
      return 'text-red-600 font-medium'
    case 'timeout':
      return 'text-yellow-600 font-medium'
    case 'parsed':
      return 'text-blue-600 font-medium'
    default:
      return 'text-gray-600'
  }
}

const getStepIcon = (step) => {
  const status = (step.status || '').toLowerCase()
  switch (status) {
    case 'success':
      return '[成功]'
    case 'failed':
      return '[失败]'
    case 'timeout':
      return '[超时]'
    case 'parsed':
      return '[已解析]'
    default:
      return '[待处理]'
  }
}
</script>

<style scoped>
.container {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.step-item {
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}

.step-item:hover {
  transform: translateX(4px);
}

.summary-card {
  box-shadow: 0 20px 40px rgba(79, 70, 229, 0.15);
}

.panel {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.panel:hover {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}
</style>
